package com.kuzlak.cms.module.sys.controller;


import cn.hutool.core.bean.BeanUtil;
import com.kuzlak.cms.bean.MyPage;
import com.kuzlak.cms.bean.Result;
import com.kuzlak.cms.constant.ResultConstant;
import com.kuzlak.cms.module.sys.bean.DictVO;
import com.kuzlak.cms.module.sys.bean.DictValueVO;
import com.kuzlak.cms.module.sys.entity.SysDict;
import com.kuzlak.cms.module.sys.entity.SysDictValue;
import com.kuzlak.cms.module.sys.service.SysDictService;
import com.kuzlak.cms.module.sys.service.SysDictValueService;
import com.kuzlak.cms.utils.RedisClient;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hesenjan(Serkol)
 * @since 2021-11-17
 */
@Tag(name = "字典管理")
@RestController
@RequestMapping("/api/dict")
public class DictController {
    @Autowired
    private SysDictService service;
    @Autowired
    private SysDictValueService valueService;
    @Autowired
    private RedisClient redisUtil;


    @Operation(summary = "字典列表")
    @PostMapping("list")
    public Result list(
            @RequestParam(name = "page", defaultValue = "0") int page,
            @RequestParam(name = "pagesize", defaultValue = "10") int pagesize,
            @Parameter(description = "开始时间") @RequestParam(name = "startDate", defaultValue = "") String startDate,
            @Parameter(description = "结束时间") @RequestParam(name = "endDate", defaultValue = "") String endDate,
            @Parameter(description = "名称") @RequestParam(name = "name", defaultValue = "") String name,
            @Parameter(description = "状态") @RequestParam(name = "status", defaultValue = "0") int status,
            @Parameter(description = "备注") @RequestParam(name = "remark", defaultValue = "") String remark,
            @Parameter(description = "字典类型") @RequestParam(name = "isKey", defaultValue = "") String isKey

    ) {
        Result gridResult = new Result();

        MyPage page1 = service.findByPage(pagesize, page, name, status, isKey, startDate, endDate, remark);


        gridResult.setData(page1);
        gridResult.setCode(ResultConstant.SUCSESS);

        return gridResult;
    }


    @Operation(summary = "添加或编辑")
    @PostMapping("edit")
    public Result edit(@RequestBody @Valid DictVO dataVo

    ) {
        SysDict data = BeanUtil.copyProperties(dataVo, SysDict.class);
        Long id = data.getId();
        if (id == null) {
            data.setId(0L);
        }


        try {
            boolean flag = false;
            if (id > 0) {
                data.setId(id);
                redisUtil.delAll("findByKeys");
                flag = service.updateById(data);
            } else {
                flag = service.save(data);
            }

            return flag ? Result.ok() : Result.failure(ResultConstant.FAIL);
        } catch (Exception e) {
            return Result.failure(ResultConstant.FAIL);
        }


    }

    @Operation(summary = "键值编辑/添加")
    //   @CacheEvict(cacheNames = {"valueListByDictId"})
    @PostMapping("valueEdit")
    public Result valueEdit(@RequestBody @Valid DictValueVO dataVo) {

        SysDictValue data = BeanUtil.copyProperties(dataVo, SysDictValue.class);
        Long id = data.getId();
        if (id == null) {
            data.setId(0L);
        }
        try {

            boolean flag = false;
            if (id > 0) {
                data.setId(id);
                redisUtil.delAll("findByKeys");
                flag = valueService.updateById(data);
            } else {
                flag = valueService.save(data);
            }

            return flag ? Result.ok() : Result.failure(ResultConstant.FAIL);
        }catch (Exception e){
            return Result.failure(ResultConstant.FAIL);
        }


    }


    @Operation(summary = "数据词典查询（编号）")
    @PostMapping("valueListByDictId")
    //   @Cacheable(cacheNames = "valueListByDictId", key = "#dictId")
    public Result valueListByDictId(@Parameter(description = "数据词典编号") @RequestParam(value = "dictId") long dictId,
                                    @Parameter(description = "值") @RequestParam(name = "isValue", defaultValue = "") String isValue,

                                    @RequestParam(name = "page", defaultValue = "0") int page,
                                    @RequestParam(name = "pagesize", defaultValue = "10") int pagesize,
                                    @Parameter(description = "名称") @RequestParam(name = "name", defaultValue = "") String name,
                                    @Parameter(description = "备注") @RequestParam(name = "remark", defaultValue = "") String remark,
                                    @Parameter(description = "状态") @RequestParam(name = "status", defaultValue = "0") int status

    ) {
        Result gridResult = new Result();

        MyPage page1 = valueService.findByPage(pagesize, page, name, status, dictId, remark, isValue);


        gridResult.setData(page1);
        gridResult.setCode(ResultConstant.SUCSESS);

        return gridResult;
    }

    @Operation(summary = "获取数据词典（关键字）")
    @PostMapping("valueListByKey")
    public Result valueListByKey(@Parameter(description = "数据词典关键字") @RequestParam(value = "dictkey") String dictkey) {

        List<SysDictValue> list = valueService.findByKey(dictkey);
        return !list.isEmpty() ? Result.ok(list) : Result.failure(ResultConstant.EMPTY_DATA);
    }

    @Operation(summary = "获取数据词典（关键字）")
    @PostMapping("valueListByKeys")
    public Result valueListByKeys(@Parameter(description = "数据词典关键字") @RequestParam(value = "dictkeys") String attrkeys) {
        Map<String, List<SysDictValue>> list = valueService.findByKeys(attrkeys);
        return !list.isEmpty() ? Result.ok(list) : Result.failure(ResultConstant.EMPTY_DATA);
    }


    @Operation(summary = "删除")
    @PostMapping("delete")
    public Result status(
            @RequestParam(name = "id", defaultValue = "0") long id
    ) {
        Result result = new Result();
        if (id > 0) {
            boolean update = service.deleteById(id);
            if (update) {
                redisUtil.delAll("findByKeys");
                result.setCode(ResultConstant.SUCSESS);
            } else {
                result.setCode(ResultConstant.FAIL);
            }
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }

        return result;
    }


    @Operation(summary = "删除")
    @PostMapping("deleteValue")
    public Result deleteValue(
            @RequestParam(name = "id", defaultValue = "0") long id
    ) {
        Result result = new Result();
        if (id > 0) {
            boolean update = valueService.deleteById(id);
            if (update) {
                redisUtil.delAll("findByKeys");
                result.setCode(ResultConstant.SUCSESS);
            } else {
                result.setCode(ResultConstant.FAIL);
            }
        } else {
            result.setCode(ResultConstant.EMPTIY);
        }

        return result;
    }
}

